import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, Not } from 'typeorm';
import BaseMachine from '@main/entities/service/admin/base/base-machine.entity';
import { ApiException } from '@main/common/exceptions/api.exception';
import { SysOperationLogService } from '../../system/operationLog/operationLog.service';

@Injectable()
export class BaseMachineService {
  constructor(
    @InjectRepository(BaseMachine)
    private machineRepository: Repository<BaseMachine>,
    private operationLogService: SysOperationLogService
  ) {}

  async list() {
    return await this.machineRepository.find();
  }

  async getMachineByMac(data) {
    const machine = await this.machineRepository.findOneBy({ mac: data.mac });

    return machine;
  }

  /**
   * 罗列所有配置
   */
  async page(data) {
    const { pageSize, pageNum, entity = {} } = data;

    const { machineName, machineCode } = entity;

    return await this.machineRepository.findAndCount({
      where: {
        machineName: Like(`%${machineName}%`),
        machineCode: Like(`%${machineCode}%`),
      },
      order: {
        updateTime: 'DESC',
      },
      take: pageSize,
      skip: (pageNum - 1) * pageSize,
    });
  }

  /**
   * 新增
   */
  async add(data, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    const machine = await this.machineRepository.insert({
      ...data,
      createName: user.nickName,
      createUserName: user.userName,
      updateName: user.nickName,
      updateUserName: user.userName,
    });
    databaseOperationLogList.push({
      type: 'add',
      dataType: 'obj',
      database: 'BaseMachine',
      checkOnlyKeyList: [],
      data: machine,
      whereObj: null,
      remark: `BaseMachine表新增数据`,
    });
    await this.operationLogService.add(
      {
        type: 'add',
        msg: `设备管理模块新增设备`,
        databaseOperationLogList,
        remark: `新增设备${data.machineName}`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 更新
   */
  async update(data, user, mac1, ip1, syncHostSqlite) {
    const databaseOperationLogList = [];
    const {
      machineName,
      mac,
      ip,
      unitNum,
      remark,
      machineStatusNegation,
      paperStatusNegation,
      hasCleanUpUnit,
      hasDieCuttingUnit,
      hasPreloadingUnit,
      hasSlottedUnit,
      hasFeedingUnit,
      factoryName,
      factoryChildName,
      machinePicture,
    } = data;

    await this.machineRepository.update(
      { id: data.id },
      {
        machineName,
        mac,
        remark,
        ip,
        unitNum,
        paperStatusNegation,
        machineStatusNegation,
        hasCleanUpUnit,
        hasDieCuttingUnit,
        hasPreloadingUnit,
        hasSlottedUnit,
        hasFeedingUnit,
        factoryName,
        factoryChildName,
        machinePicture,
        updateName: user.nickName,
        updateUserName: user.userName,
      }
    );

    databaseOperationLogList.push({
      type: 'update',
      dataType: 'obj',
      database: 'BaseMachine',
      checkOnlyKeyList: [],
      data: {
        machineName,
        mac,
        remark,
        ip,
        unitNum,
        paperStatusNegation,
        machineStatusNegation,
        hasCleanUpUnit,
        hasDieCuttingUnit,
        hasPreloadingUnit,
        hasSlottedUnit,
        hasFeedingUnit,
        factoryName,
        factoryChildName,
        machinePicture,
        updateName: user.nickName,
        updateUserName: user.userName,
      },
      whereObj: { id: data.id },
      remark: `BaseMachine表更新设备信息`,
    });
    await this.operationLogService.add(
      {
        type: 'update',
        msg: `设备管理模块更新设备信息`,
        databaseOperationLogList,
        remark: `更新设备${data.machineName}`,
        mac: mac1,
        ip: ip1,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 删除
   */
  async delete(idList, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    await this.machineRepository.delete(idList);
    databaseOperationLogList.push({
      type: 'delete',
      dataType: 'array',
      database: 'BaseMachine',
      checkOnlyKeyList: [],
      data: null,
      whereObj: idList,
      remark: `BaseMachine表删除设备`,
    });
    await this.operationLogService.add(
      {
        type: 'delete',
        msg: `设备管理模块删除设备`,
        databaseOperationLogList,
        remark: `删除设备`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  async isExistKey(machineCode: string) {
    const result = await this.machineRepository.findOne({ where: { machineCode } });

    if (result) {
      throw new ApiException(10023);
    }
  }

  async isExistMac(dto) {
    if (dto.mac) {
      const result = await this.machineRepository.findOne({
        where: { mac: dto.mac, machineCode: Not(dto.machineCode) },
      });
      if (result) {
        throw new ApiException(10024);
      }
    }
  }

  async isExistIp(dto) {
    if (dto.ip) {
      const result = await this.machineRepository.findOne({
        where: { mac: dto.ip, machineCode: Not(dto.ip) },
      });
      if (result) {
        throw new ApiException(10038);
      }
    }
  }
}
